import Vue from 'vue'
import VueRouter from 'vue-router'
import layout from '@/views/layout'
import login from '@/views/login'
import myOrder from '@/views/myOrder'
import pay from '@/views/pay'
import proDetail from '@/views/proDetail'
import search from '@/views/search/index.vue'
import searchList from '@/views/search/list.vue'
import home from '@/views/layout/home'
import category from '@/views/layout/category'
import cart from '@/views/layout/cart'
import user from '@/views/layout/user'
import phoneLogin from '@/views/phoneLogin/index.vue'
import register from '@/views/register'
import address from '@/views/address/index.vue'
import set from '@/views/set/index.vue'
import store from '@/store'
import { Toast } from 'vant'
Vue.use(VueRouter)
const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: layout,
      redirect: '/home',
      children: [
        { path: 'home', component: home },
        { path: 'category', component: category },
        { path: 'cart', component: cart },
        { path: 'user', component: user }
      ]
    },
    { path: '/login', component: login },
    { path: '/phoneLogin', component: phoneLogin },
    { path: '/register', component: register },
    { path: '/myOrder', component: myOrder },
    { path: '/pay', component: pay },
    { path: '/proDetail', component: proDetail },
    { path: '/search', component: search },
    { path: '/searchList', component: searchList },
    { path: '/address', component: address },
    { path: '/set', component: set }
  ]
})
router.beforeEach((to, from, next) => {
  const forbidRoute = ['/myOrder', '/pay', 'address']
  if (!forbidRoute.includes(to.path)) {
    next()
    return
  }
  const token = store.state.user.userInfo.token
  if (token) {
    next()
  } else {
    Toast('请先登录')
    next('/login')
  }
})
export default router
